package com.medicine.service.impl;

import com.medicine.constant.MessageConstant;
import com.medicine.dto.UserLoginDTO;
import com.medicine.entity.User;
import com.medicine.exception.LoginFailedException;
import com.medicine.mapper.UserMapper;
import com.medicine.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        
        // 判断用户名和密码是否为空
        if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        
        // 对密码进行加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        
        // 根据用户名和密码查询用户
        User user = userMapper.getByUsernameAndPassword(username, password);
        
        // 判断用户是否存在
        if (user == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        
        // 返回用户对象
        return user;
    }
}